import Article from '../../type'
import React, { useEffect, useState } from 'react'
import style from './style.module.less'
import { Viewer } from '@bytemd/react'
import gfm from '@bytemd/plugin-gfm'
import math from '@bytemd/plugin-math'
import highlight from '@bytemd/plugin-highlight-ssr'
import mermaid from '@bytemd/plugin-mermaid'
import mediumZoom from '@bytemd/plugin-medium-zoom'
import { EyeOutlined } from '@ant-design/icons'
import { Avatar, Button, message, Tag } from 'antd'
import * as api from '../../services/api'
import { TweenOneGroup } from 'rc-tween-one'
import { Link } from 'react-router-dom'

export default function ArticleItem(props: any) {
  let token: string = props.token
  let changeUpdate = props.changeUpdate
  let update: boolean = props.update

  const data: Article = props.dataSource
  const plugins = [gfm(), math(), highlight(), mermaid(), mediumZoom()]

  const [url, setUrl] = useState<string>('')
  const [button, setButton] = useState<boolean>(props.button)

  useEffect(() => {
    getAvatar(data.banner[0])
  }, [])

  let tagChile = data.tags.split(',').map((tag) => (
    <Tag key={tag} color={'gold'}>
      {tag}
    </Tag>
  ))

  function getTime(str: number) {
    const date = new Date(str)
    let month: string | number = date.getMonth() + 1
    let strDate: string | number = date.getDate()
    let hour: string | number = date.getHours()
    let min: string | number = date.getMinutes()

    if (month <= 9) month = '0' + month
    if (strDate <= 9) strDate = '0' + strDate
    if (hour <= 9) hour = '0' + hour
    if (min <= 9) min = '0' + min

    return `${date.getFullYear()}年${month}月${strDate}日${hour}时${min}分`
  }

  async function getAvatar(str: string) {
    try {
      if (str.length > 0) {
        let res = await api.previewFile(str)
        setUrl((window.URL || window.webkitURL).createObjectURL(res.data))
      }
    } catch (e) {
      throw e
    }
  }

  async function deleteArticle() {
    try {
      let res = await api.deleteArticle(token, data.id)
      if (res.data.stat === 'ok') {
        changeUpdate(!update)
      } else {
        message.destroy()
        message.error(res.data.msg)
      }
    } catch (e) {
      throw e
    }
  }

  return (
    <div className={style.ArticleOfAvatar}>
      <div className={style.Article}>
        <Link
          to={{
            pathname: `/articleDetail/${token}`,
            state: { data: data, url: url, back: button },
          }}>
          <h1 className={style.ArticleTitle}>{data.title}</h1>
        </Link>
        <div className={style.ArticleMain}>
          {button ? (
            <></>
          ) : (
            <span className={style.ArticleAuthor}>
              作者：{data.author}&nbsp;&nbsp;&nbsp;&nbsp;
            </span>
          )}
          <span className={style.ArticleCTime}>
            创建时间：{getTime(data.ctime)}&nbsp;&nbsp;&nbsp;&nbsp;
          </span>
          <EyeOutlined />
          <span className={style.ArticlePreview}>&nbsp;{data.preview}</span>
        </div>
        <div className={style.ArticleTags}>
          <TweenOneGroup
            enter={{
              scale: 0.8,
              opacity: 0,
              type: 'from',
              duration: 100,
            }}
            leave={{ opacity: 0, width: 0, scale: 0, duration: 200 }}
            appear={false}>
            {tagChile}
          </TweenOneGroup>
        </div>
        <div className={style.ArticleContent}>
          <Viewer plugins={plugins} value={data.content.split('\n')[0]} />
        </div>
      </div>
      {!!url ? (
        <Avatar className={style.ArticleAvatar} src={`${url}`} />
      ) : (
        <></>
      )}
      {button ? (
        <div className={style.ArticleButton}>
          <Link
            to={{
              pathname: `/articleSet/${token}`,
              state: {
                id: data.id,
                title: data.title,
                tags: data.tags,
                content: data.content,
              },
            }}>
            <Button className={style.ArticleButtonSet}>编辑</Button>
          </Link>
          <Button className={style.ArticleButtonDel} onClick={deleteArticle}>
            删除
          </Button>
        </div>
      ) : (
        <></>
      )}
    </div>
  )
}
